#include "page3_tcp.h"
#include "ui_page3_tcp.h"

page3::page3(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::page3)
{
    ui->setupUi(this);
    this->setFixedSize(1280,720);

//################################################
//#                                              #
//#           设置界面3背景                        #
//#           最后一次修改4.9，11：16               #
//#                                              #
//################################################
    QPixmap widget_background = QPixmap(":/ocean.jpg");
    widget_background = widget_background.scaled(1280,720,Qt::KeepAspectRatio);
    QPixmap temp_background(widget_background.size());
    temp_background.fill(Qt::transparent);
    //白色透明度
    //    QPainter picture_background(&temp_background);
    //    picture_background.setCompositionMode(QPainter::CompositionMode_Source);
    //    picture_background.drawPixmap(0,0,widget_background);
    //    picture_background.setCompositionMode(QPainter::CompositionMode_DestinationIn);

    //    picture_background.fillRect(widget_background.rect(),QColor(0,0,0,150));
    //    picture_background.end();

    //    widget_background = temp_background;
    //黑色透明度
    QPainter picture_background(&widget_background);
    picture_background.setCompositionMode(QPainter::CompositionMode_Source);
    picture_background.drawPixmap(0,0,widget_background);
    picture_background.setCompositionMode(QPainter::CompositionMode_DestinationIn);

    picture_background.fillRect(widget_background.rect(),QColor(0,0,0,210));
    picture_background.end();

    ui->label_background->setPixmap(widget_background);

//set tablewidget transparent  ___________________________________________________________________________________________?????????????????
//    ui->tabWidget->setStyleSheet("background-color: rgba(0,0,0,1);");	//整个表格透明,但是会将子控件也设置为透明的.
//  尝试使用qpalette但是没用
//    QPalette pll = ui->tabWidget->palette();
//    pll.setBrush(QPalette::Base,QBrush(QColor(0,0,0,0)));
//    ui->tabWidget->setPalette(pll);


//################################################
//#                                              #
//#           网络通信初始化                       #
//#           最后一次修改4.9，8：51                #
//#                                              #
//################################################
//tcp客户端初始化
    socket_client = new QTcpSocket();
    QObject::connect(socket_client, &QTcpSocket::readyRead, this, &page3::socket_client_Read_Data);
    QObject::connect(socket_client, &QTcpSocket::disconnected, this, &page3::socket_client_Disconnected);
    ui->pushButton_client_Send->setEnabled(false);
    ui->lineEdit_client_IP->setText("192.168.20.59");
    ui->lineEdit_client_Port->setText("8765");
//tcp服务器端初始化
    ui->lineEdit_server_Port->setText("8765");
    ui->pushButton_server_Send->setEnabled(false);
    server = new QTcpServer();
    connect(server,&QTcpServer::newConnection,this,&page3::server_New_Connect);
//udp通讯相关初始化
    this->timer_push = new QTimer(this);
    connect(timer_push,&QTimer::timeout,this,&page3::show_push_image);
    ui->lineEdit_udp_ip->setText("192.168.20.59");
    ui->lineEdit_udp_port->setText("6666");
    this->udp_socket = new QUdpSocket(this);
//    QObject::connect(udp_socket,&QUdpSocket::readyRead,this,&page3::udp_read_data);
    udp_socket->bind(QHostAddress::Any,8888);
    is_push_frame = 0;
}

page3::~page3()
{
    timer_push->stop();
    delete this->socket_server;
    delete this->socket_client;
    delete this->timer_push;
    server->close();
    server->deleteLater();
    delete ui;
}

//################################################
//#                                              #
//#           窗口切换相关函数                      #
//#           最后一次修改4.9，7：51                #
//#                                              #
//################################################
void page3::on_pushButton_page1_clicked()
{
    emit pushbutton_page1_clicked();
}


void page3::on_pushButton_page2_clicked()
{
    emit pushbutton_page2_clicked();
}


void page3::on_pushButton_page3_clicked()
{
    emit pushbutton_page3_clicked();
}


void page3::on_pushButton_page4_clicked()
{
    emit pushbutton_page4_clicked();
}

//################################################
//#                                              #
//#           tcp客户端相关函数                    #
//#           最后一次修改4.9，10:54               #
//#                                              #
//################################################


//############tcp客户端####################
//########################################
void page3::on_pushButton_client_Send_clicked()
{
//    qDebug() << "Send: " << ui->textEdit_Send->toPlainText();
    //在客户端发送时写入客户端通话记录
    QString test_client = ui->textEdit_client_Recv->toPlainText();
    test_client += "\n";
    test_client += "客户端：\n    ";
    test_client += ui->textEdit_client_Send->toPlainText();
    ui->textEdit_client_Recv->setText(test_client);
    //获取文本框内容并以ASCII码形式发送
    socket_client->write(ui->textEdit_client_Send->toPlainText().toLatin1());
    ui->textEdit_client_Send->clear();
    socket_client->flush();
}

void page3::on_pushButton_client_Connect_clicked()
{
    if(ui->pushButton_client_Connect->text() == tr("连接"))
    {
        QString IP;
        int port;

        //获取IP地址
        IP = ui->lineEdit_client_IP->text();
        //获取端口号
        port = ui->lineEdit_client_Port->text().toInt();

        qDebug()<<"test1\n";

        //取消已有的连接
        socket_client->abort();
        //连接服务器
        socket_client->connectToHost(IP, port);

        //等待连接成功
        if(!socket_client->waitForConnected(30000))
        {
            qDebug() << "Connection failed!";
            return;
        }
        qDebug() << "Connect successfully!";

        //发送按键使能
        ui->pushButton_client_Send->setEnabled(true);
        //修改按键文字
        ui->pushButton_client_Connect->setText("断开连接");
    }
    else
    {
        //断开连接
        socket_client->disconnectFromHost();
        //修改按键文字
        ui->pushButton_client_Connect->setText("连接");
        ui->pushButton_client_Send->setEnabled(false);
    }
}

void page3::socket_client_Read_Data()
{
    QByteArray buffer;
    //读取缓冲区数据
    buffer = socket_client->readAll();

    //    debug看回信
            int size = buffer.size();
            for(int i = 0; i<size ;i++){
                qDebug()<<"debug : buffer["<<i<<"] = "<<(unsigned char)buffer.at(i);
            }
            qDebug()<<"\n";

    if(!buffer.isEmpty())
    {
        //在服务器端发送时写入客户端通话记录
        QString str = ui->textEdit_client_Recv->toPlainText();
        str += "\n服务器端:\n    ";
        str += tr(buffer);
        //刷新显示
        ui->textEdit_client_Recv->setText(str);
    }
}

void page3::socket_client_Disconnected()
{
    //发送按键失能
    ui->pushButton_client_Send->setEnabled(false);
    //修改按键文字
    ui->pushButton_client_Connect->setText("连接");
    qDebug() << "Disconnected!";
}

void page3::on_pushButton_client_clean_clicked()
{
    ui->textEdit_client_Recv->clear();
}



//################################################
//#                                              #
//#           tcp服务器端相关函数                   #
//#           最后一次修改4.9，10:54               #
//#                                              #
//################################################

//############tcp服务器端##################
//########################################
void page3::on_pushButton_server_Send_clicked()
{
//    qDebug() << "Send: " << ui->textEdit_Send->toPlainText();
    //在服务器端发送时写入服务器端通话记录
    QString test_server = ui->textEdit_server_Recv->toPlainText();
    test_server += "\n";
    test_server += "服务器端：\n    ";
    test_server += ui->textEdit_server_Send->toPlainText();
    ui->textEdit_server_Recv->setText(test_server);
    //获取文本框内容并以ASCII码形式发送
    socket_server->write(ui->textEdit_server_Send->toPlainText().toLatin1());
    ui->textEdit_server_Send->clear();
    socket_server->flush();
}


void page3::on_pushButton_server_Listen_clicked()
{
    if(ui->pushButton_server_Listen->text() == tr("侦听"))
    {
        //从输入框获取端口号
        int port = ui->lineEdit_server_Port->text().toInt();

        //监听指定的端口
        if(!server->listen(QHostAddress::Any, port))
        {
            //若出错，则输出错误信息
            qDebug()<<server->errorString();
            return;
        }
        //修改按键文字
        ui->pushButton_server_Listen->setText("取消侦听");
        qDebug()<< "Listen succeessfully!";
    }
    else
    {
        //如果正在连接
        if(socket_server->state() == QAbstractSocket::ConnectedState)
        {
            //关闭连接
            socket_server->disconnectFromHost();
        }
        //取消侦听
        server->close();
        //修改按键文字
        ui->pushButton_server_Listen->setText("侦听");
        //发送按键失能
        ui->pushButton_server_Send->setEnabled(false);
    }
}

void page3::server_New_Connect()
{
    //获取客户端连接
    socket_server = server->nextPendingConnection();
    //连接QTcpSocket的信号槽，以读取新数据
    QObject::connect(socket_server, &QTcpSocket::readyRead, this, &page3::socket_server_Read_Data);
    QObject::connect(socket_server, &QTcpSocket::disconnected, this, &page3::socket_server_Disconnected);
    //发送按键使能
    ui->pushButton_server_Send->setEnabled(true);

    qDebug() << "A Client connect!";
}

void page3::socket_server_Read_Data()
{
    QByteArray buffer;
    //读取缓冲区数据
    buffer = socket_server->readAll();
    if(!buffer.isEmpty())
    {
        //在客户端发送时写入服务器端通话记录
        QString str = ui->textEdit_server_Recv->toPlainText();
        str += "\n客户端：\n    ";
        str += tr(buffer);
        //刷新显示
        ui->textEdit_server_Recv->setText(str);
    }
}

void page3::socket_server_Disconnected()
{
    //发送按键失能
    ui->pushButton_server_Send->setEnabled(false);
    qDebug() << "Disconnected!";
}

void page3::on_pushButton_server_clean_clicked()
{
    ui->textEdit_server_Recv->clear();
}


//################################################
//#                                              #
//#           udp视频推流相关                      #
//#           最后一次修改4.9，19：59               #
//#                                              #
//################################################

void page3::reload_frame_push(cv::Mat frame_pass)
{
    this->frame_push = frame_pass;
    return;
}

void page3::show_push_image()
{
//视频显示
    cv::Mat frame_temp;
    frame_push.copyTo(frame_temp);
    cv::cvtColor(frame_temp,frame_temp,cv::COLOR_BGR2RGB);
    QImage image((unsigned char *)(frame_temp.data),frame_temp.cols,frame_temp.rows,QImage::Format_RGB888);
    ui->label_push_frame->setPixmap(QPixmap::fromImage(image));

//udp推流
    if(is_push_frame == 0)  return;
    //设置udp的目标ip地址和端口
        QHostAddress udp_ip = (QHostAddress)(ui->lineEdit_udp_ip->text());
        quint16 udp_port = ui->lineEdit_udp_port->text().toInt();

    //读取并且旋转图片
        cv::transpose(frame_temp,frame_temp);
        cv::flip(frame_temp,frame_temp,1);

    //构建图片发送的数据
        QImage image_push((unsigned char *)(frame_temp.data),frame_temp.cols,frame_temp.rows,QImage::Format_RGB888);
        QByteArray byte;
        QBuffer buffer(&byte);
        buffer.open(QIODevice::WriteOnly);
        image_push.save(&buffer,"JPEG");
        QByteArray ss = qCompress(byte,5);

    //发送图片
        //    QByteArray ss = ui->lineEdit_ip->text().toUtf8();
        if(udp_socket->writeDatagram(ss,udp_ip,udp_port)){
            qDebug()<<"write ok "<<udp_ip<<" "<<udp_port<<Qt::endl;
        }

    return;
}

void page3::on_pushButton_udp_open_clicked()
{
    if(ui->pushButton_udp_open->text() == "打开摄像头"){
        ui->pushButton_udp_open->setText("关闭摄像头");
        timer_push->start(30);
    }else if(ui->pushButton_udp_open->text() ==  "关闭摄像头"){
        timer_push->stop();
        ui->label_push_frame->clear();
        ui->label_push_frame->setText("没有视频显示");
    }
}


void page3::on_pushButton_udp_push_clicked()
{
    if(ui->pushButton_udp_open->text() == "关闭摄像头"){
        if(ui->pushButton_udp_push->text() == "打开推流"){
            ui->pushButton_udp_push->setText("关闭推流");
            is_push_frame = 1;
        }else if(ui->pushButton_udp_push->text() == "关闭推流"){
            ui->pushButton_udp_push->setText("打开推流");
            is_push_frame = 0;
        }
    }else {
        qDebug()<<"没有视频数据，无法推流\n";
    }
    return;
}

//################################################
//#                                              #
//#           串转网通信服务器发送模块               #
//#           最后一次修改4.9，19：59               #
//#                                              #
//################################################

void page3::send_data_from_client(QByteArray data_send)
{
        //debug
        int size = data_send.size();
        for(int i = 0; i<size ;i++){
            qDebug()<<"debug_send_upup_tcp : data["<<i<<"] = "<<(unsigned char)data_send.at(i);
        }
        qDebug()<<"\n";
    socket_client->write(data_send);
    qDebug()<<"client send correct!\n";
}
